package com.itheima.web.controller;

import com.github.pagehelper.PageInfo;
import com.itheima.constant.MessageConstant;
import com.itheima.domain.Question;
import com.itheima.domain.Result;
import com.itheima.factory.BeanFactory;
import com.itheima.service.QuestionService;
import com.itheima.utils.BeanUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@WebServlet("/store/question/*")
public class QuestionServlet extends BaseServlet {
    QuestionService questionService = BeanFactory.getBean("questionService",QuestionService.class);
    private Result delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取请求参数并封装
        try {
            String[] ids = BeanUtil.fillBeanFromJson(request, String[].class);
            //调用service层edit方法,执行删除操作
            questionService.delete(ids);
            //响应客户端
            return new Result(true,MessageConstant.DELETE_QUESTION_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true,MessageConstant.DELETE_QUESTION_FAIL);
        }
    }

    private Result edit(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取请求参数并封装
        try {
            Question question = BeanUtil.fillBeanFromJson(request, Question.class);
            //调用service层edit方法,执行保存操作
            questionService.edit(question);
            //响应客户端
            return new Result(true,MessageConstant.EDIT_QUESTION_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true,MessageConstant.EDIT_QUESTION_FAIL);
        }
    }

    private Result findById(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            //1.获取请求参数
            String questionId = request.getParameter("id");
            //调用service层方法,获取查询结果
            Question question = questionService.findById(questionId);
            //对客户端做出响应
            return new Result(true, MessageConstant.QUERY_QUESTION_SUCCESS,question);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_QUESTION_FAIL);
        }
    }

    private Result save(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取请求参数并封装
        try {
            Question question = BeanUtil.fillBeanFromJson(request, Question.class);
            //调用service层save方法,执行保存操作
            questionService.save(question);
            //响应客户端
            return new Result(true,MessageConstant.SAVE_QUESTION_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true,MessageConstant.SAVE_QUESTION_FAIL);
        }
    }

    //处理分页查询的请求
    private Result findByPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            //1.获取请求参数
            String strCurrentPage = request.getParameter("currentPage");
            String strPageSize = request.getParameter("pageSize");
            //1.1判断非空
            int currentPage = 1,pageSize = 5;
            if(!StringUtils.isBlank(strCurrentPage)){
                currentPage = Integer.parseInt(strCurrentPage);
            }
            if(!StringUtils.isBlank(strPageSize)){
                pageSize = Integer.parseInt(strPageSize);
            }
            //调用service层方法,获取查询结果
            PageInfo<Question> pageInfo = questionService.findByPage(currentPage,pageSize);
            //对客户端做出响应
            return new Result(true, MessageConstant.QUERY_QUESTION_SUCCESS,pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_QUESTION_FAIL);
        }
    }

    //处理分页查询的请求
    private Result findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            List<Question> list = questionService.findAll();
            //对客户端做出响应
            return new Result(true, MessageConstant.QUERY_QUESTION_SUCCESS,list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_QUESTION_FAIL);
        }
    }

    //处理文件上传
    private Result upload(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            //1.创建DiskFileItemFactory磁盘工厂对象
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //2.创建ServletFileUpload文件上传核心对象
            ServletFileUpload fileUpload = new ServletFileUpload(factory);
            //3.解析请求,获取所有表单项FileItems
            List<FileItem> fileItems = fileUpload.parseRequest(request);
            //3.1 本项目中每次上传只会上传一张图片
            FileItem fileItem = fileItems.get(0);
            //4.将图片写到服务器硬盘中
            //4.1 获取文件保存的目录
            String realPath = getServletContext().getRealPath("/upload");
            //4.2 获取文件名
            String filename = fileItem.getName();//abc.jpg
            //确保图片名称唯一,使用UUID生成一个唯一的字符串作为文件名
            String uuid = UUID.randomUUID().toString().replace("-", "");
            //获取原文件的后缀名
            String suffix = filename.substring(filename.lastIndexOf("."));
            //组合新的文件名
            filename=uuid+suffix;
            //4.3 将图片写到磁盘中
            fileItem.write(new File(realPath,filename));
            return new Result(true,MessageConstant.UPLOAD_QUESTIONIMG_SUCCESS,filename);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true,MessageConstant.UPLOAD_QUESTIONIMG_FAIL);
        }
    }

    //导出Excel表格
    private Result toExport(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //需求:在servlet中读取excel模板,将数据写到excel中,然后在servlet使用文件下载技术发送给客户端
        try {
            //1.设置Content-disposition响应头
            response.setHeader("Content-disposition","attachment;filename=question.xlsx");
            //2.调用service层方法,生成xlsx表格，进行报表导出
            questionService.toExport(response.getOutputStream());
            return new Result(true, MessageConstant.QUERY_QUESTION_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_QUESTION_FAIL);
        }
    }
}
